<template>
  <div>
    <head-top></head-top>
  </div>
  <div class="item_center" v-loading="loading" element-loading-background="rgba(122, 122, 122, 0.8)"
       element-loading-text="疯狂加载中...">
    <div class="body_box">
      <el-row style="width: 1200px;;margin-top: 30px;margin-bottom: 20px">
        <el-col :span="12">
          <el-image :src="require('@/assets/website_logo.png')" style="height: 80px" @click="goHome"></el-image>
        </el-col>
        <el-col :span="12">
          <el-steps
              :active="2"
              finish-status="success"
              align-center
          >
            <el-step title="下单"/>
            <el-step title="填写订单信息"/>
            <el-step title="提交订单"/>
          </el-steps>
        </el-col>
      </el-row>
      <el-card>
        <template #header>
          <div class="card-header">
            <span>填写并核对订单信息</span>
          </div>
        </template>
        <div class="address_box">
          <el-card class="box-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>收货人信息</span>
                <el-button class="button" text @click="openAddAddressDialog=true">新增收货地址</el-button>
              </div>
            </template>
            <el-row :gutter="10" v-if="selectAddress!=null">
              <el-col :span="2">
                <el-text truncated><span>{{ selectAddress.name }}</span></el-text>
              </el-col>
              <el-col :span="15">
                <p>
                  收货人： {{ selectAddress.name }}
                </p>
                <p>
                  地址： {{ selectAddress.province }}{{ selectAddress.city }}{{ selectAddress.region }}
                </p>
                <p>
                  联系方式： {{ selectAddress.phone }}
                </p>
                详细地址：{{ selectAddress.detailAddress }}
              </el-col>
              <el-col :span="2"><span>默认地址</span></el-col>
              <el-col :span="4">
                <div>
                  <el-dropdown @visible-change="getAddressList">
                      <span class="el-dropdown-link">
                        <el-text type="primary">选择其他地址</el-text>
                        <el-icon class="el-icon--right">
                          <arrow-down/>
                        </el-icon>
                      </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item v-for="item in addressList" :key="item.id">{{ item.name }}：
                          <el-text>{{ item.detailAddress }}</el-text>
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </el-col>
            </el-row>
            <div v-else>你还没有收货地址! <span style="color: red" @click="openAddAddressDialog=true">立即创建</span>
            </div>
          </el-card>
          <el-card shadow="hover">
            <template #header>
              <span>支付方式</span>
            </template>
            <el-row>
              <el-col :span="3">
                <span style="color: gray">货到付款</span>
              </el-col>
              <el-col :span="3">
                <span style="border: solid red">在线支付</span>
              </el-col>
            </el-row>
          </el-card>
        </div>
        <!--     购买信息与商家信息     -->
        <div>
          <el-card shadow="hover">
            <template #header>
              <span>购买信息与商家信息</span>
            </template>
            <div>
              <el-table :data="skuItemVo" style="width: 100%">
                <el-table-column label="预览">
                  <template #default="scope">
                    <el-image :src="$img+scope.row.defultImgId"></el-image>
                  </template>
                </el-table-column>
                <el-table-column prop="skuTitle" label="商品标题"/>
                <el-table-column prop="saleAttrValue" label="商品规格"/>
                <el-table-column prop="price" label="商品单价"/>
                <el-table-column prop="brandName" label="品牌信息"/>
                <el-table-column prop="buyNumber" label="购买数量">
                </el-table-column>
                <el-table-column label="总价">
                  <template #default="scoped">
                    {{ scoped.row.price * scoped.row.buyNumber }}
                  </template>
                </el-table-column>
                <el-table-column label="店铺信息">
                  <template #default="scope">
                    <el-icon>
                      <!--                        <el-image :src="$img+scope.row.bussinessImg"></el-image>-->
                    </el-icon>
                    <span>{{ scope.row.businessName }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </div>
        <div>
          <el-card>
            <template #header>
              <span>配送信息</span>
            </template>
            <div>
              <span class="detail-title">寄送至</span>：<span>{{ selectAddress?.detailAddress }}</span>
              <br/>
              <span class="detail-title">收货人</span> : {{ selectAddress?.name }}<span></span>
              <br/>
              <span class="detail-title">运费</span>
              ：{{ orderSaveDto.freight }}
            </div>
          </el-card>
        </div>
        <div style="padding: 14px">
          <div class="bottom">
            <span>合计:{{ orderSaveDto.orderPrice }}元</span>&nbsp;&nbsp;
            <button class="sub_btn" @click="submitOrder"><span style="color: white">提交订单</span></button>
          </div>
        </div>
      </el-card>
    </div>
  </div>
  <foot style="margin-top:20px "></foot>
  <div>
    <el-dialog
        v-model="openAddAddressDialog"
        title="新增收货地址"
        width="40%"
        :before-close="handleClose"
        @close="addRef.resetFields()"
    >
      <div>
        <el-form :model="addressDetil" label-width="100" size="large" ref="addRef">
          <el-form-item label="收货人姓名" prop="name">
            <el-input v-model="addressDetil.name"></el-input>
          </el-form-item>
          <el-form-item label="邮政编码" prop="postCode">
            <el-input v-model="addressDetil.postCode"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="addressDetil.phone"></el-input>
          </el-form-item>
          <el-form-item label="省份/城市/区">
            <elui-china-area-dht @change="onChange"></elui-china-area-dht>
          </el-form-item>
          <el-form-item label="详细地址" prop="detailAddress">
            <el-input type="textarea" v-model="addressDetil.detailAddress"></el-input>
          </el-form-item>
          <el-form-item label="省市区代码" prop="areacode">
            <el-input v-model="addressDetil.areacode" disabled></el-input>
          </el-form-item>
          <el-form-item label="是否默认" prop="defaultStatus">
            <el-switch v-model="addressDetil.defaultStatus" :inactive-value="1" :active-value="0"/>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="openAddAddressDialog = false">取消</el-button>
        <el-button type="primary" @click="saveAddress">
          保存
        </el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ArrowDown, ArrowLeftBold} from '@element-plus/icons-vue'
import {EluiChinaAreaDht} from 'elui-china-area-dht'
import {addAddressApi, getDefaultAddressApi, getAddressListApi} from "@/api/memberReceiveAddress";
import {onMounted, reactive, ref} from "vue";
import {useRouter, useRoute} from "vue-router";
import {getSkuItemApi, getOrderConfirmSkuInfo} from "@/api/goods";
import {getFreightApi} from "@/api/warehouse";
import {getOrderTokenApi, saveOrderApi} from '@/api/order'
import HeadTop from "@/components/home/HeadTop";
import Foot from "@/components/home/Foot";

const router = useRouter()
const chinaData = new EluiChinaAreaDht.ChinaArea().chinaAreaflat
let loading = ref(true)
const route = useRoute()
let selectAddress = ref({})
let addressList = ref([])
let addRef = ref()
let openAddAddressDialog = ref(false)
let buyInfo = JSON.parse(route.query.data)
let orderType = route.query.type
//新增地址
let addressDetil = reactive({
  name: '',
  phone: '',
  postCode: '',
  province: '',
  city: '',
  region: '',
  detailAddress: '',
  areacode: '',
  defaultStatus: 0,
})
let skuItemVo = ref([])//封装sku的详细信息
let orderSaveDto = reactive({
  addressId: '',
  token: '',
  freight: 0,
  orderPrice: '',
  orderISaveItemDtos: [],
  orderType: 0//默认为零（普通订单）
})

function getDefaultAddress() {
//  获取默认收货地址
  getDefaultAddressApi().then(res => {
    if (res.data) {
      selectAddress.value = res.data
      getFreight()
    }
  })
}

function goHome() {
  router.push("/")
}

function getSkuInfo() {
  let skuIds = buyInfo.map(item => {
    return item.skuId
  })
  getOrderConfirmSkuInfo([...skuIds]).then(res => {
    //设置每一个sku的购买数量
    buyInfo.forEach(item => {
      res.data.forEach(item2 => {
        if (item2.skuId === item.skuId) {
          item2.buyNumber = item.buyNumber
          //如果是秒杀订单，则将随机码token传值
          if (item.token != null && item.token !== '' && orderType == 1) {
            item2.skuToken = item.token
          }
        }
      })
    })
    skuItemVo.value = res.data
  })
}

function back() {
  //返回上一个路由
  router.go(-1)
}

function getAddressList() {
  getAddressListApi().then(res => {
    addressList.value = res.data
  })
}

/**
 * 地址选择器绑定数据
 * @param e
 */
function onChange(e) {
  const one = chinaData[e[0]]
  const two = chinaData[e[1]]
  const three = chinaData[e[2]]
  /*省区名称*/
  addressDetil.province = one.label
  addressDetil.city = two.label
  addressDetil.region = three.label
  /* 省市区代码*/
  addressDetil.areacode = one.value + ',' + two.value + ',' + three.value
}

/**
 * 新增收货地址
 */
function saveAddress() {
  addAddressApi(addressDetil).then(() => {
    //  刷新
    return getDefaultAddress()
  })
  openAddAddressDialog.value = false
}

/**
 * 获取运费
 */
function getFreight() {
  getFreightApi(selectAddress.value.id).then(res => {
    orderSaveDto.freight = res.data
    getOrderPrice()
  })
}


function getOrderPrice() {
  orderSaveDto.orderPrice = orderSaveDto.freight;
  skuItemVo.value.forEach(item => {
    orderSaveDto.orderPrice += item.price * item.buyNumber
  })
}

/**
 * 提交订单
 */
function submitOrder() {
//封装订单提交数据
  orderSaveDto.addressId = selectAddress.value.id
  //计算价格
  getOrderPrice()
  //订单类型
  orderSaveDto.orderType = orderType
  //遍历购买的sku信息，构建传回的DTO
  orderSaveDto.orderISaveItemDtos = skuItemVo.value.map(item => {
    return {
      skuId: item.skuId,
      buyNumber: item.buyNumber,
      skuToken: item.skuToken
    }
  })
  //生成订单，返回订单号
  saveOrderApi(orderSaveDto).then(res => {
    // 跳转订单详情页 并将订单编号传入
    router.push({
      path: "/order-detail",
      query: {
        orderId: res.data
      }
    })
  })
}

/**
 * 获取订单防重令牌
 */
function getOrderToken() {
  getOrderTokenApi().then(res => {
    orderSaveDto.token = res.data.token
  })
}

onMounted(() => {
  getDefaultAddress()
  getSkuInfo()
  getOrderToken()
  setTimeout(() => {
    loading.value = false
  }, 1000)
})
</script>

<style scoped>
.body_box {
  display: flex;
  width: 1200px;
  flex-direction: column;
  justify-content: center;
}

.item_center {
  display: flex;
  justify-content: center;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
  display: flex;
  justify-content: end;
  align-items: center;
}

.button {
  padding: 0;
  min-height: auto;
}

.sub_btn {
  width: 100px;
  height: 40px;
  background-color: red;
  border-style: none;
}

.detail-title {
  color: red;
  font-size: large;
}
</style>
